package com.kaka.starter.token.util;

import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.NoSuchElementException;

/**
 * @author kaka
 * @Date 2022/3/10
 */
public class HeaderUtils {

    public static final String USER_INFO = "X-SFJ-UserInfo";
    public static final String AUTHORIZATION = "Authorization";
    public static final String USER_ID = "_id";

    private static String auth;
    private static String authSecret;

    public static void setAuth(String auth) {
        HeaderUtils.auth = auth;
    }

    public static void setAuthSecret(String authSecret) {
        HeaderUtils.authSecret = authSecret;
    }

    public static JWTUtils.JWTResult getHeader() {
        HttpServletRequest request =
                ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        JWTUtils.JWTResult jwtResult = JWTUtils.parse(
                request.getHeader(auth), authSecret);
        try {
            JWTUtils.addJWTResut2LocalCache(jwtResult);
            return  jwtResult;
        } catch (Exception e) {
            throw new NoSuchElementException("get token error ");
        }
    }

    public static String getToken() {
        return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes())
                .getRequest().getHeader(AUTHORIZATION);
    }

    public static String getHeaderString() {
        return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes())
                .getRequest().getHeader(USER_INFO);
    }

    public static Integer getUserId() {
        return HeaderCommon.getUserId(getHeader());
    }
    public static List<Integer> getQueryGroups() {
        return HeaderCommon.getQueryGroups(getHeader());
    }
    public static String getUserName() {
        return HeaderCommon.getUserName(getHeader());
    }

    public static int getTenantId() {
        return HeaderCommon.getTenantId(getHeader());
    }

    public static Integer getUserGroupIds() {
        return HeaderCommon.getUserGroupIds(getHeader());
    }

    public static Integer getUserDept() {
        return HeaderCommon.getUserDept(getHeader());
    }
    public static String getUserLevel() {
        return HeaderCommon.getUserLevel(getHeader());
    }

    public static Integer getRoleId() {
        return HeaderCommon.getRoleIds(getHeader());
    }
}
